package com.yuma.communication;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class MyNumber2{
    public static int number = 0;
    public ReentrantLock lock = new ReentrantLock();
    public Condition condition1 = lock.newCondition();
    public Condition condition2 = lock.newCondition();

    public void incr(){
        lock.lock();

        while (number != 0) {
            try {
                System.out.println( Thread.currentThread().getName() + "进入等待池");
                condition1.await();
                System.out.println( Thread.currentThread().getName() + "出等待池");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println( Thread.currentThread().getName() + ":number自增到了" + ++number);
        condition2.signal();
        lock.unlock();
    }

    public void decr(){
        lock.lock();
        while(number != 1){
            try {
                System.out.println( Thread.currentThread().getName() + "进入等待池");
                condition2.await();
                System.out.println( Thread.currentThread().getName() + "出等待池");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println( Thread.currentThread().getName() + ":number自减到了" + --number);
        condition1.signal();  // 把自增线程唤醒
        lock.unlock();
    }
}


public class ConditionDemo {
    public static void main(String[] args) {
        MyNumber2 myNumber = new MyNumber2();

        for(int i = 0; i < 5; i++) {
            new Thread(() -> {
                myNumber.incr();
            }, "自增:"+String.valueOf(i)).start();
        }

        for(int i = 0; i < 5; i++) {
            new Thread(() -> {
                myNumber.decr();
            }, "自减:" +String.valueOf(i)).start();
        }
    }
}
